package cc.z8g.browser

import android.content.Intent
import android.graphics.Color
import android.os.Bundle
import android.view.Menu
import androidx.annotation.StyleRes
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.withStyledAttributes
import androidx.core.graphics.drawable.DrawableCompat
import androidx.core.view.iterator
import cc.z8g.browser.utils.sp.UserSp
import cc.z8g.browser.utils.ThemeUtils

/**
 * 一个主题感知的活动，根据用户的偏好更新其主题。
 */
abstract class ThemableBrowserActivity : AppCompatActivity() {

    private var themeId: Int = UserSp.THEME_LIGHT
    private var shouldRunOnResumeActions = false

    /** 重写此方法以提供一个替代主题，该主题应设置为此活动的每个实例，而不考虑用户的偏好设置。*/
    @StyleRes
    protected open fun getCustomThemeResId(): Int = when (UserSp.getInt(UserSp.KEY_THEME)) {
        UserSp.THEME_DARK -> R.style.Theme_DarkTheme
        UserSp.THEME_BLACK -> R.style.Theme_BlackTheme
        else -> R.style.Theme_LightTheme
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        themeId = UserSp.getInt(UserSp.KEY_THEME)
        setTheme(getCustomThemeResId())
        super.onCreate(savedInstanceState)
        resetPreferences()
    }

    override fun onCreateOptionsMenu(menu: Menu): Boolean {
        withStyledAttributes(attrs = intArrayOf(R.attr.iconColorState)) {
            val iconTintList = getColorStateList(0)
            for (item in menu) {
                val icon = item.icon ?: continue
                DrawableCompat.setTintList(DrawableCompat.wrap(icon), iconTintList)
            }
        }

        return super.onCreateOptionsMenu(menu)
    }

    private fun resetPreferences() {
        window.statusBarColor = if (UserSp.getBoolean(UserSp.KEY_BLACK_STATUS_BAR)) Color.BLACK else ThemeUtils.getStatusBarColor(this)
    }

    override fun onWindowFocusChanged(hasFocus: Boolean) {
        super.onWindowFocusChanged(hasFocus)
        if (hasFocus && shouldRunOnResumeActions) {
            shouldRunOnResumeActions = false
            onWindowVisibleToUserAfterResume()
        }
    }

    /** 在活动恢复后调用，并且 UI 对用户可见。仅在 onResume 被调用后，由 onWindowFocusChanged 调用。 */
    protected open fun onWindowVisibleToUserAfterResume() = Unit

    override fun onResume() {
        super.onResume()
        resetPreferences()
        shouldRunOnResumeActions = true
        if (themeId != UserSp.getInt(UserSp.KEY_THEME)) {
            restart()
        }
    }

    protected fun restart() {
        finish()
        startActivity(Intent(this, javaClass))
    }
}
